package com.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CountDownLatch 可以使一个线程等待其它线程执行结束后再执行在CountDownLatch上等待的线程
 */
@Slf4j
public class CountDownLatchExample {
    private static int threadCount = 200;

    public static void main(String[] args) throws Exception{
        //1.初始化时定义计数器数值
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executor.execute(()->{
                try{
                    doSth(threadNum);

                }catch (Exception e){
                    log.error("错误：", e);
                }finally {
                    //2.每个线程根据处理完城后调用，计数器数值-1
                    countDownLatch.countDown();
                }
            });
        }
        //3.判断计数器数值是否为0，如果为0唤醒当前线程，否则继续等待
        countDownLatch.await();
        log.info("finish");
        executor.shutdown();
    }

    public static void doSth(int threadNum) throws Exception{
        Thread.sleep(10);
        log.info("线程：{}", threadCount);
    }
}
